package com.runfast.waimai.web.controller;

import com.gxuc.runfast.bean.Business;
import com.runfast.common.dao.model.RunfastCuser;
import com.runfast.common.security.spring.UserDataDetails;
import com.runfast.common.service.RunfastCuserService;
import com.runfast.common.utils.GPSUtil;
import com.runfast.common.utils.TokenUtil;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static sun.security.krb5.Confounder.intValue;

/**
 * 商户接口
 */
@RestController("userWmBusinessController")
@RequestMapping(value = "/api/user/wm/business")
public class BusinessController {


    @Autowired
    private RunfastBusinessService businessService;

    @Autowired
    private RunfastBusinessCommentService businessCommentService;

    @Autowired
    private RunfastDistributionassessService distributionassessService;

    @Autowired
    private RunfastGoodsSellRecordService goodsSellRecordService;

    @Autowired
    private RunfastCuserService cuserService;


    @Autowired
    private RunfastActivityService activityService;

    /**
     * 获取商家详情
     *
     * @param businessId 商户id
     * @return
     */
    @PostMapping("/detail")
    public Result detail(@RequestParam int businessId, @RequestParam double userLng, @RequestParam double userLat) {

        /**
         * 高德转百度
         */
        double[] to = GPSUtil.gcj02_To_Bd09(userLat, userLng);
        userLng = to[1];
        userLat = to[0];

        return businessService.detail(businessId, userLng, userLat);
    }


    /**
     * 添加订单评论
     * @param orderId 订单id
     * @param comment 评论
     * @param businessScore 商家得分
     * @param businessTags 商家标签
     * @param driverScore 骑手得分
     * @param driverTags 骑手标签
     * @param token
     * @return
     */
    @PostMapping("/addComment")
    public Result addComment(@RequestParam int orderId, String comment,
                             @RequestParam(required = false) Integer businessScore, @RequestParam(required = false) String businessTags,
                             @RequestParam(required = false) Integer driverScore, @RequestParam(required = false) String driverTags,
                             @RequestParam(required = false) Integer tasteScore,@RequestParam(required = false) Integer packagesScore,
                             @RequestParam(required = false) Boolean anonymous,@RequestParam(required = false) Boolean driverSatisfy, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);


//        Validate.notBlank(comment, "评论内容不能为空");
        Validate.notNull(businessScore, "给商家评个分吧");
        if(!(businessScore>=1&&businessScore<=5)) return Result.fail(ResultCode.FAIL, "评分必须在1到5分范围内");


        RunfastGoodsSellRecord goodsSellRecord = goodsSellRecordService.selectByPrimaryKey(orderId);
        if (goodsSellRecord == null) return Result.fail(ResultCode.FAIL, "订单不存在");

        Integer isComent = goodsSellRecord.getIsComent();
        if(isComent!=null) return Result.fail(ResultCode.FAIL, "已经评论过");

        Integer isDeliver = goodsSellRecord.getIsDeliver();
        Integer businessId = goodsSellRecord.getBusinessId();
        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);

        RunfastBusinessComment businessComment = new RunfastBusinessComment();

        RunfastBusiness business = businessService.selectByPrimaryKey(businessId);
        businessComment.setAgentId(business.getAgentId());
        businessComment.setAgentName(business.getAgentName());

        businessComment.setContent(comment);
        businessComment.setBusinessId(businessId);
        businessComment.setBusinessName(goodsSellRecord.getBusinessName());

//        businessComment.setGoodsSellId(goodsSellRecord.getGoodsSellId());
//        businessComment.setGoodsSellName(goodsSellRecord.getGoodsSellName());

        businessComment.setOrderCode(goodsSellRecord.getOrderCode());
        businessComment.setGoodsSellRecordId(goodsSellRecord.getId());

        businessComment.setUserId(goodsSellRecord.getUserId());
        businessComment.setUserName(cuser.getNickname());
        businessComment.setPic(cuser.getPic());

        businessComment.setCost(goodsSellRecord.getTotalpay().doubleValue());

        businessComment.setDelicerId(goodsSellRecord.getShopperId());
        businessComment.setDelicerName(goodsSellRecord.getShopper());

        businessComment.setCreateTime(new Date());
        businessComment.setOrderTime(goodsSellRecord.getCreateTime());
        businessComment.setShangstr(businessTags);

        businessComment.setScore(Double.valueOf(businessScore));
        businessComment.setTasteScore(tasteScore);
        businessComment.setPackagesScore(packagesScore);
        businessComment.setAnonymous(anonymous);
        businessComment.setDriverSatisfy(driverSatisfy);
        businessCommentService.insertSelective(businessComment);

        RunfastGoodsSellRecord goodsSellRecordUpdate = new RunfastGoodsSellRecord();
        goodsSellRecordUpdate.setId(goodsSellRecord.getId());
        if (isDeliver != null && isDeliver == 1) {

            goodsSellRecordUpdate.setIsComent(1);//是否评价；null：未评价 1：已评价商家， 2：全部评价

        } else {
//            Validate.notNull(driverScore, "给骑手评个分吧");
            //骑手评价
            RunfastDistributionassess distributionAssess = new RunfastDistributionassess();

            //订单
            distributionAssess.setOrderNumber(goodsSellRecord.getOrderCode());
            distributionAssess.setGoodsSellRecordId(goodsSellRecord.getId());

            //评价人
            distributionAssess.setAssessId(goodsSellRecord.getUserId());
            distributionAssess.setAssessman(cuser.getNickname());


            distributionAssess.setAssessTime(new Date());
            distributionAssess.setConsume(goodsSellRecord.getPrice());//金额

            //评价信息
//            distributionAssess.setScore(Double.valueOf(driverScore));

//            businessComment.setDelicerScore(Double.valueOf(driverScore));

            //骑手没有评论内容
//            distributionAssess.setContent(comment);

            //配送人员
            distributionAssess.setShopperId(goodsSellRecord.getShopperId());
            distributionAssess.setShopperName(goodsSellRecord.getShopper());
            distributionAssess.setDistributionTime(goodsSellRecord.getReadyTime());

            distributionAssess.setAgentId(business.getAgentId());
            distributionAssess.setAgentName(business.getAgentName());
            distributionAssess.setQishoustr(driverTags);
            distributionassessService.insertSelective(distributionAssess);

            goodsSellRecordUpdate.setIsComent(2);//是否评价；null：未评价 1：已评价商家， 2：全部评价

        }



        goodsSellRecordService.updateByPrimaryKeySelective(goodsSellRecordUpdate);


        /**
         * 更新商家积分
         */

        RunfastBusiness businessUpdate = new RunfastBusiness();
        businessUpdate.setId(businessId);

        Integer score = business.getScore();
        score = score==null?0:score;
        businessUpdate.setScore(score+businessScore);
        businessService.updateByPrimaryKeySelective(businessUpdate);

        return Result.ok("");
    }


    @PostMapping("/reComment")
    public Result reComment(@RequestParam int commentId, @RequestParam(required = false) String comment, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);


        Validate.notBlank(comment, "评论内容不能为空");


        RunfastBusinessComment businessComment = businessCommentService.selectByPrimaryKey(commentId);
        if(businessComment==null) return Result.fail(ResultCode.FAIL, "评价不存在，请先评价");


        RunfastBusinessComment businessCommentUpdate = new RunfastBusinessComment();
        businessCommentUpdate.setId(commentId);
        businessCommentUpdate.setRecontent(comment);
        businessCommentUpdate.setRecreateTime(new Date());


        businessCommentService.updateByPrimaryKeySelective(businessCommentUpdate);

        return Result.ok("");
    }


    @PostMapping("/deleteComment")
    public Result deleteComment(@RequestParam int commentId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);


        RunfastBusinessComment businessComment = businessCommentService.selectByPrimaryKey(commentId);
        if(businessComment==null) return Result.fail(ResultCode.FAIL, "评论不存在");


        Integer orderId = businessComment.getGoodsSellRecordId();


        RunfastBusinessComment businessCommentUpdate = new RunfastBusinessComment();
        businessCommentUpdate.setId(businessComment.getId());
        businessCommentUpdate.setDeleted(true);

        businessCommentService.updateByPrimaryKeySelective(businessCommentUpdate);


        /**
         * 更新订单
         */
//        RunfastGoodsSellRecord goodsSellRecordUpdate = new RunfastGoodsSellRecord();
//        goodsSellRecordUpdate.setId(goodsSellRecord.getId());
//        goodsSellRecordUpdate.setIsComent(null); //重置

        //将订单i是Comment置为null
        goodsSellRecordService.resetIsComent(orderId);


        /**
         * 更新商家积分
         */
        RunfastBusiness business = businessService.selectByPrimaryKey(businessComment.getBusinessId());
        RunfastBusiness businessUpdate = new RunfastBusiness();
        businessUpdate.setId(business.getId());

        Integer score = business.getScore();
        score = score==null?0:score;
        Double commentScore = businessComment.getScore();
        commentScore = commentScore ==null?0d:commentScore;
        if(score>= commentScore){

            businessUpdate.setScore(score-commentScore.intValue());
            businessService.updateByPrimaryKeySelective(businessUpdate);
        }


        return Result.ok("");
    }

    /**
     * 获取商家下的用户评论
     *
     * @param businessId 商户idred
     * @param pageable
     * @return
     */
    @PostMapping("/listComment")
    public Result listComment(@RequestParam int businessId, @PageableDefault Pageable pageable) {


        List<RunfastBusinessComment> businessCommentList = businessCommentService.find(businessId,null,pageable);


        Map<String, Object> stat = businessCommentService.businessCommentStat(businessId,null);


        Long count = 0L;
        Integer totalScore = 0;

        if (stat != null) {
            count = (Long) stat.get("count");
            count = count==null?0L:count;

            Double totalScoreTemp = (Double)stat.get("totalScore");
            totalScoreTemp = totalScoreTemp ==null?0d:totalScoreTemp;
            totalScore = totalScoreTemp.intValue();
        }




        RunfastBusiness businessUpdate = new RunfastBusiness();
        businessUpdate.setId(businessId);
        businessUpdate.setScore(totalScore.intValue());

        businessService.updateByPrimaryKeySelective(businessUpdate);
        BigDecimal totalTasteScore = (BigDecimal)stat.get("totalTasteScore");
        BigDecimal totalPackagesScore = (BigDecimal)stat.get("totalPackagesScore");

        RunfastBusiness business = businessService.selectByPrimaryKey(businessId);
        Integer businessScore = business.getScore();
        businessScore = businessScore ==null?0:businessScore;
        double avgScore = count==0?0d:BigDecimal.valueOf(businessScore).divide(BigDecimal.valueOf(count),1, RoundingMode.HALF_UP).doubleValue();

        totalTasteScore = totalTasteScore==null? BigDecimal.valueOf(0):totalTasteScore;
        double avgTastescore  = count==0?0d:totalTasteScore.divide(BigDecimal.valueOf(count),1, RoundingMode.HALF_UP).doubleValue();

        totalPackagesScore = totalPackagesScore==null?BigDecimal.valueOf(0):totalPackagesScore;
        double avgPackagesScore  = count==0?0d:totalPackagesScore.divide(BigDecimal.valueOf(count),1, RoundingMode.HALF_UP).doubleValue();


        Map<String, Object> commentMap = new HashMap<>();
        commentMap.put("commentCount", count);
        commentMap.put("commentList", businessCommentList);
        commentMap.put("avgScore", avgScore);
        commentMap.put("avgTastescore", avgTastescore);
        commentMap.put("avgPackagesScore", avgPackagesScore);

        return Result.ok("",commentMap);
    }


    /**
     * 商家代金券
     * @param businessId
     * @return
     */
    @PostMapping("/redActivityForPick")
    public Result redActivityForPick(@RequestParam int businessId) {

        UserDataDetails<RunfastCuser> principal = (UserDataDetails<RunfastCuser>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        RunfastCuser cuser = principal.getData();

        return activityService.businessRedActivityForPick(businessId, cuser.getId());
    }


    /**
     * 下单返红包
     * @param orderId
     * @return
     */
    @PostMapping("/returnActivityForPick")
    public Result returnActivityForPick(@RequestParam int orderId) {

        UserDataDetails<RunfastCuser> principal = (UserDataDetails<RunfastCuser>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        RunfastCuser cuser = principal.getData();

        return activityService.returnActivityForPick(orderId, cuser.getId());
    }




}
